<template>
    <div>
        <UserForm :user="user" :mode="mode" @submit="handleSubmit" />
    </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue';
import UserForm from './UserForm.vue';

export default defineComponent({
    name: 'UserContainer',
    components: {
        UserForm,
    },
    props: {
        initialUser: {
            type: Object as () => { name: string; email: string },
            default: () => ({ name: '', email: '' }),
        },
        mode: {
            type: String as () => 'view' | 'edit' | 'add',
            required: true,
        },
    },
    emits: ['submit'],
    setup(props, { emit }) {
        const user = ref({ ...props.initialUser });

        watch(
            () => props.initialUser,
            (newUser) => {
                user.value = { ...newUser };
            },
            { deep: true }
        );

        const handleSubmit = (updatedUser: { name: string; email: string }) => {
            emit('submit', updatedUser);
        };

        return {
            user,
            handleSubmit,
        };
    },
});
</script>